package Q4;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;

public class ChatClient {

    public static void main(String[] args) {
        //socket对象链接服务器
        Scanner sc = null;
        ObjectOutputStream clientOutputStream = null;
        ObjectInputStream clientInputStream = null;
        try {
            Socket s = new Socket("127.0.0.1", 8887);
            System.out.println("连接服务器成功！");

            sc = new Scanner(System.in);
            clientOutputStream = new ObjectOutputStream(s.getOutputStream());
            clientInputStream = new ObjectInputStream(s.getInputStream());
            while (true) {
                //键盘输入user message信息
                System.out.println("请输入用户名");
                String name = sc.next();
                System.out.println("请输入密码");
                String password = sc.next();
                System.out.println("请输入请求类型");
                String msgType = sc.next();
                //发送数据
                UserMessage message = new UserMessage(msgType, new User(name, password));
                clientOutputStream.writeObject(message);
                System.out.println("----客户端发送message = " + message);

                Object readObject = clientInputStream.readObject();
                message = readObject instanceof UserMessage ? (UserMessage) readObject : null;
                System.out.println("----客户端接收message = " + message);
            }
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (clientInputStream != null) {
                    clientInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (clientOutputStream != null) {
                    clientOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (sc != null) {
                sc.close();
            }
        }

    }
}
